import glob
import re
from concurrent.futures import ThreadPoolExecutor
from compements.target_url import process_admin  # 导入重构后的函数


def main():
    # 1. 查找所有admin_n.txt文件（如./文档/admin_1.txt）
    admin_files = glob.glob("./文档/admin_*.txt")
    if not admin_files:
        print("未找到admin_n.txt文件")
        return False  # 返回执行状态

    # 2. 提取编号n（如admin_1.txt -> 1）
    tasks = []
    for file in admin_files:
        match = re.search(r'admin_(\d+)\.txt', file)
        if match:
            n = match.group(1)
            tasks.append((file, n))
        else:
            print(f"忽略无效文件：{file}")

    try:
        with ThreadPoolExecutor(max_workers=min(len(tasks), 8)) as executor:# 创建线程池
            # 使用列表保存future对象
            futures = []
            for file, n in tasks:
                future = executor.submit(process_admin, file, n)# 提交任务
                futures.append(future)

            # 等待所有任务完成并检查结果
            for future in futures:
                try:
                    future.result()  # 获取任务执行结果，会抛出异常如果任务执行失败
                except Exception as e:
                    print(f"任务执行出错: {e}")
                    return False  # 返回执行失败状态

        print("所有任务执行成功")
        return True  # 返回执行成功状态

    except Exception as e:
        print(f"程序执行过程中发生异常: {e}")
        return False


def run_with_retry(max_retries=3):
    """带重试功能的程序运行函数"""
    for attempt in range(1, max_retries + 1):
        print(f"程序第 {attempt} 次运行开始")
        success = main()
        if success:
            print("程序执行成功")
            return
        else:
            if attempt < max_retries:
                print(f"程序执行失败，5秒后重新开始...")
                import time
                time.sleep(5)
            else:
                print("已达到最大重试次数，程序退出")


if __name__ == "__main__":
    run_with_retry()
